import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:pornhub_app/components/base_refresh/base_refresh_controller.dart';
import 'package:pornhub_app/components/pay/enum_pay.dart';
import 'package:pornhub_app/components/pay/model/recharge_type_model.dart';
import 'package:pornhub_app/components/pay/pay_view.dart';
import 'package:pornhub_app/model/mine/group_members_model.dart';
import 'package:pornhub_app/views/mine/vip/buy_hint_dialog.dart';

import '../../../components/base_refresh/base_refresh_page_counter.dart';
import '../../../http/api/api.dart';
import '../../../services/user_service.dart';

class GroupMembersController extends BaseRefreshController
    with BaseRefreshPageCounter {
  final PagingController<int, GroupMembersModel> pagingController =
      PagingController(firstPageKey: 1);
  final us = Get.find<UserService>();
  var payUrl = ''.obs;

  @override
  Future<IndicatorResult> onRefresh() async {
    resetPage();
    return await getMembersList(isRefresh: true);
  }

  @override
  Future<IndicatorResult> onLoad() async {
    incPage();
    return await getMembersList();
  }

  Future<IndicatorResult> getMembersList({bool isRefresh = false}) async {
    try {
      if (isRefresh) {
        pagingController.refresh();
      }
      final response = await Api.getGroupMembersList(page: page);
      if (response!.isNotEmpty) {
        _addList(response);
        pagingController.appendPage(response, page);
        return IndicatorResult.success;
      } else {
        if (isRefresh) {
          pagingController.appendLastPage([]);
          return IndicatorResult.success;
        } else {
          pagingController.appendLastPage([]);
          return IndicatorResult.noMore;
        }
      }
    } catch (e) {
      return IndicatorResult.fail;
    }
  }

  void _addList(List<GroupMembersModel>? list) {
    if (null != list && list.isNotEmpty) {
      for (int i = 0; i < list.length; i++) {
        list[i].types?.add(RechargeTypeModel.balance());
      }
    }
  }

  onSubmitGold(GroupMembersModel model) async {
    await Get.bottomSheet(
      isScrollControlled: true,
      BuyHintDialog(onTap: () async {
        await Get.bottomSheet(
          PayView(
            amount: (model.groupPrice ?? 0).toDouble(),
            payId: model.groupId ?? 0,
            purType: PurTypeEnum.groupBuy,
            payType: model.types ?? [],
          ),
        );
        onRefresh();
      }),
    );
  }
}
